/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jeelabs.lab2;

import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.application.Application;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;

/**
 *
 * @author bastian
 */
@ManagedBean(name="EditHelperBean")
@SessionScoped
public class EditHelperBean implements Serializable {

    @Resource
    private UserTransaction utx;

    @PersistenceContext
    private EntityManager em;

    private Dragon dragon;

    private boolean edycja;

    /** Creates a new instance of EditHelperBean */
    public EditHelperBean() {
    }

    public Dragon getDragon() {
        return dragon;
    }

    public String edytuj() {
        FacesContext context = FacesContext.getCurrentInstance();
        Application application = context.getApplication();
        ExpressionFactory factory = application.getExpressionFactory();
        ValueExpression valueExpression = factory.createValueExpression(context.getELContext(), "#{Dragon}", Dragon.class);
        dragon = (Dragon) valueExpression.getValue(context.getELContext());
        edycja = true;

        return "lab2_edit";
    }

    public String nowa() {
        dragon = new Dragon();
        edycja = false;

        return "lab2_edit";
    }

    public String zatwierdz() {
        try {
            utx.begin();
            if (edycja) {
                em.merge(dragon);
            } else {
                em.persist(dragon);
                Cave c = (Cave) em.createQuery("SELECT k FROM Cave k WHERE k.id = " + dragon.getCave().getId()).getSingleResult();
//                Cave c = dragon.getCave(); czemu to nie dziala ? 
                c.getDragonCollection().add(dragon);
            }
            utx.commit();
        } catch (Exception ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Problem z transakcja", ex);
        }

        dragon = null;

        return "lab2";
    }

    public String usun() {
        FacesContext context = FacesContext.getCurrentInstance();
        Application application = context.getApplication();
        ExpressionFactory factory = application.getExpressionFactory();
        ValueExpression valueExpression = factory.createValueExpression(context.getELContext(), "#{Dragon}", Dragon.class);
        Dragon k = (Dragon) valueExpression.getValue(context.getELContext());
        try {
            utx.begin();
            k = em.merge(k);
            em.remove(k);
//            Cave c = (Cave) em.createQuery("SELECT k FROM Cave k WHERE k.id = " + k.getCave().getId()).getSingleResult();
            Cave c = k.getCave();
            c.getDragonCollection().remove(k);
            utx.commit();
        } catch (Exception ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Problem z transakcja", ex);
        }

        return "lab2";
    }
    
    public String zapytanieJPA() {
        try {
            utx.begin();
            em.createQuery("UPDATE Dragon d SET d.fireColor = 'Red'").executeUpdate();
            utx.commit(); 
        } catch (Exception ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Problem z transakcja", ex);
        }
       
        return "lab2";
    }
//
//    /* Metody przykładowe niewykorzystane w przykładzie */
//    public void zapytanieZArgumentami() {
//        EntityManager em = ((EntityManagerFactory) FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get("emf")).createEntityManager();
//        Query q = em.createQuery("Autor.findByNazwisko");
//        q.setParameter("nazwisko", "Kosakowska");
//        List wynik = q.getResultList();
//        em.close();
//    }
//
//    public void zapytaniaNiePredefiniowane() {
//        EntityManager em = ((EntityManagerFactory) FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get("emf")).createEntityManager();
//        List wyniki = em.createQuery("SELECT DISTINCT a.imie FROM Autor a").getResultList();
//        wyniki = em.createQuery("SELECT k FROM Ksiazka k where k.autor.nazwisko = 'Kres'").getResultList();
//        em.close();
//    }

}
